package com.xuan.yubi.manager;

import com.xuan.yubi.common.ErrorCode;
import com.xuan.yubi.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class RedisLimiterManager {

    @Resource
    private RedissonClient redissonClient;

    /**
     *  根据 userId 限制每个用户每秒只能操作 2 次
     * @param userId 用户id
     */
    public void doRateLimit(String userId) {
        RRateLimiter limiter = redissonClient.getRateLimiter(userId);
        // Initialization required only once.
        // 2 permits per 1 seconds
        limiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);

        // acquire 3 permits or block until they became available
        boolean canOperation = limiter.tryAcquire();
        if (!canOperation) {
            // 调用频率过高，限制调用
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }

    public void doRateLimitOnlyOne(String userId) {
        RRateLimiter limiter = redissonClient.getRateLimiter(userId);
        // Initialization required only once.
        // 2 permits per 1 seconds
        limiter.trySetRate(RateType.OVERALL, 1, 1, RateIntervalUnit.SECONDS);

        // acquire 3 permits or block until they became available
        boolean canOperation = limiter.tryAcquire();
        if (!canOperation) {
            // 调用频率过高，限制调用
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }

}
